<?php

namespace Portal\ContractBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Portal\ContractBundle\Entity\Contract;
use Portal\NotificationBundle\Entity\Notification;
use Portal\ContractBundle\Entity\Invoice;
use Portal\ContractBundle\Entity\Ticket;

class ContractMoreController extends Controller
{ 
  private $activeStatus = "('created')";
  private $completeStatus = "('complete')";
  private $availableStatus = "('created', 'complete', 'userDenied')";
  
  public function firstLessonUserSubmitAction(Request $request)
  {
     if ($request->getMethod() != 'POST') {
      $this->get('session')->setFlash('error', 'Зөвшөөрөгдөөгүй хандалт!');
      return $this->redirect($this->generateUrl('logout'));
    }

    // GET POST VALUES
    $postValues = $request->request;
    $contractId = $postValues->get('contractId');
    $contractContent = $postValues->get('contractContent');

    if (strlen(trim($contractContent)) == 0) {
      $this->get('session')->setFlash('error', 'Гэрээ буруу байна!');
      return $this->redirect($this->generateUrl('homepage'));
    }


    // CRETERIA
    $contract = $this->getDoctrine()->getEntityManager()->getRepository('PortalContractBundle:Contract')->findBy(array('id' => $contractId, 'isActive' => $this->container->getParameter('statusActive')));
    
    // CHECK CONTRACT
    if (!$contract) {
      $this->get('session')->setFlash('error', 'Уучлаарай энэ гэрээ байхгүй байна!');
      return $this->redirect($this->generateUrl('logout'));
    }
    
    $contract = $contract[0];

    // CHECK CONTRACT IS LEGAL
    $contractCheck = $this->checkContractIsLegal($contractId, $this->completeStatus);
    if ($contractCheck == false) {
      $this->get('session')->setFlash('error', 'Уучлаарай энэ гэрээ танд ирээгүй байна!');
      return $this->redirect($this->generateUrl('homepage'));
    }

    if (isset($_POST['firstLessonAgree'])) {

      
      $contract->setStatus($this->container->getParameter('contractStatusStarted'));
      
      $em = $this->getDoctrine()->getManager();
      $em->persist($contract);
      $em->flush();

      $this->addNotificationForFirstLesson($contract, 'Анхны хичээл орлоо гэж сурагч тэмдэглэлээ.');

      $this->addTicketForRate($contract);
      
      if ($contract->getId()) {
        $this->get('session')->setFlash('notice', 'Гэрээг амжилттай хадгаллаа.');
        return $this->redirect($this->generateUrl('homepage'));
      }
    } elseif (isset($_POST['firstLessonDisagree'])) {

      // SET CONTRACT STATUS TO USER DENIED
      $contract->setStatus($this->container->getParameter('contractStatusUserDenied'));
      $contract->setUserFlag($this->container->getParameter('contractUserFlagNo'));
      $contract->setIsActive($this->container->getParameter('statusInActive'));
      $em = $this->getDoctrine()->getManager();
      $em->persist($contract);
      $em->flush();

      // SET LESSON STATUS TO USER DENIED
      $lesson = $contract->getLesson();
      $lessonStatus = $this->getDoctrine()->getEntityManager()->getRepository('PortalContractBundle:LessonStatus')->find($this->container->getParameter('lessonStatusUserDenied'));
      $lesson->setStatus($lessonStatus);
      $em = $this->getDoctrine()->getManager();
      $em->persist($lesson);
      $em->flush();

      $this->addNotificationForFirstLesson($contract, 'Анхны хичээл орсонгүй, Сурагч гэрээг цуцаллаа гэж сурагч тэмдэглэлээ.');

      if ($contract->getId()) {
        $this->get('session')->setFlash('notice', 'Хичээл заалгах гэрээг цуцаллаа');
        return $this->redirect($this->generateUrl('homepage'));
      }
    } else {
      $this->get('session')->setFlash('error', 'Зөвшөөрөгдөөгүй хандалт!');
      return $this->redirect($this->generateUrl('logout'));
    }
  }
  
  private function checkContractIsLegal($contractId, $status)
  {
    $user = $this->checkUser();
    if (in_array($this->container->getParameter('ROLE_USER'), $user->getRoles())) {
      $userRole = 'ROLE_USER';
    } else if (in_array($this->container->getParameter('ROLE_TUTOR'), $user->getRoles())) {
      $userRole = 'ROLE_TUTOR';
    } else {
      return false;
    }

    $contract = $this->getDoctrine()->getEntityManager()->getRepository('PortalContractBundle:Contract')->checkThisContractIsLegal($contractId, $status, $userRole, $user->getId());
    
    if ($contract) {
      return $contract;
    } else {
      return false;
    }
  }
  
  private function addNotificationForFirstLesson($contract, $notificationText)
  {
    $user = $this->checkUser();
    $contractId = $contract->getId();
    
    $notificationType = $this->container->getParameter('notificationContract');
    $toUrl = $this->container->getParameter('notificationUrlContract') . $contractId;
    $tableId = $contractId;
    $description = $notificationText;
    $tutorId = $contract->getLesson()->getTutor()->getId();
    $userId = $contract->getLesson()->getUser()->getId();
    $status = $this->container->getParameter('notificationStatusUnread');
    $isActive = $this->container->getParameter('statusActive');
    $createdAt = new \DateTime();

    $lastInsertedId = $this->saveNotification($notificationType, $tableId, $toUrl, $description, $tutorId, $userId, $status, $isActive, $createdAt, null, $this->container->getParameter('contractDirectionToTutor'));

    return $lastInsertedId;
  }
  
  private function checkUser()
  {
    $user = $this->container->get('security.context')->getToken()->getUser();

    if ($user) {
      if (!is_object($user)) {
        header('Location: /logout');
        die;
      }

      if (is_array($user->getRoles()) == FALSE) {
        header('Location: /logout');
        die;
      }

      return $user;
    } else {
      header('Location: /logout');
      die;
    }
  }
  
  /**
   * Notification хадгалах
   * 
   * @param type $noificationType
   * @param type $tableId
   * @param type $toUrl
   * @param type $description
   * @param type $tutorId
   * @param type $userId
   * @param type $status
   * @param type $isActive
   * @param type $createdAt
   */
  private function saveNotification($notificationType, $tableId, $toUrl, $description, $tutorId, $userId, $status, $isActive, $createdAt, $userRole = null, $tutorRole = null)
  {
    $notification = new Notification();
    $notification->setNotificationType($notificationType);
    $notification->setTableId($tableId);
    $notification->setToUrl($toUrl);
    $notification->setDescription($description);
    $notification->setTutorId($tutorId);
    $notification->setUserId($userId);
    $notification->setIsActive($isActive);
    $notification->setCreatedAt($createdAt);
    $notification->setUpdatedAt(new \DateTime());
    if (isset($userRole)) {
      $notification->setUserShowPermission($this->container->getParameter('contractDirectionToUser'));
      $notification->setStatus($status);
    }

    if (isset($tutorRole)) {
      $notification->setTutorShowPermission($this->container->getParameter('contractDirectionToTutor'));
      $notification->setStatusTutor($status);
    }

    $em = $this->getDoctrine()->getManager();
    $em->persist($notification);
    $em->flush();

    return $notification->getId();
  }
  
  public function addTicketForRate($contract)
  {
      $ticketType = $this->container->getParameter('ticketTypeRate');      
      $user = $contract->getUser();
      $status = $this->container->getParameter('statusActive');
      $createdAt = new \DateTime();      
      
      $ticket = new Ticket();
      $ticket->setTicketType($ticketType);
      $ticket->setContract($contract);
      $ticket->setUser($user);
      $ticket->setStatus($status);
      $ticket->setCreatedAt($createdAt);
      $em = $this->getDoctrine()->getManager();
      $em->persist($ticket);
      $em->flush();
      
      return $ticket->getId();
  }
  
}
